package com.gd.iot.energy.util;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @Description:
 * @Author: zgyz
 * @Date: 2020/8/13 0:24
 */
@Component("customSpringUtil")
@Lazy(false)
public final class CustomSpringUtil implements ApplicationContextAware, DisposableBean
{
    private static ApplicationContext applicationContext;

    private CustomSpringUtil() {
    }

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) {
        CustomSpringUtil.applicationContext = applicationContext;
    }

    @Override
    public void destroy() throws Exception {
        CustomSpringUtil.applicationContext = null;
    }

    public static ApplicationContext getApplicationContext() {
        return CustomSpringUtil.applicationContext;
    }

    public static Object getBean(final String name) {
        Assert.hasText(name, "Bean name can't be empty!");
        return CustomSpringUtil.applicationContext.getBean(name);
    }

    public static <T> T getBean(final String name, final Class<T> type) {
        Assert.hasText(name, "Bean name can't be empty!");
        Assert.notNull((Object)type, "class type can't be null!");
        return (T)CustomSpringUtil.applicationContext.getBean(name, (Class)type);
    }

    public static String getMessage(final String code, final Object... args) {
        final LocaleResolver localeResolver = getBean("localeResolver", LocaleResolver.class);
        final Locale locale = localeResolver.resolveLocale((HttpServletRequest)null);
        return CustomSpringUtil.applicationContext.getMessage(code, args, locale);
    }
}
